package com.example.springbootdemo.Controller;

import com.example.springbootdemo.utils.ApiResult;
import com.example.springbootdemo.utils.Base64;
import com.example.springbootdemo.utils.PassToken;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.Base64Utils;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
public class CodeController {
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Value("char")
    private String captchaType;

    @Autowired
    private RedisTemplate redisTemplate;
    @PassToken
    @GetMapping("/getCheckCode")
    public ApiResult getCheckCode(HttpServletResponse response){
        String uuid = UUID.randomUUID()+"";
        String verifyKey = "captcha_codes:"+uuid;
        String capStr = null,code=null;
        BufferedImage image = null;
        capStr = code = captchaProducer.createText();  //45EE
        image = captchaProducer.createImage(capStr);   //创建验证码图片
        redisTemplate.opsForValue().set(verifyKey,code,2, TimeUnit.MINUTES);
        //转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image,"jpg",os);
        } catch (IOException e) {
            return ApiResult.createByFail(200,"获取验证码失败");
        }
        Map<String,Object> map = new HashMap<>();
        map.put("uuid",uuid);
        map.put("img", Base64.encode(os.toByteArray()));      //输出流转换为base64编码
        return ApiResult.createBySuccess(200,map,"获取成功");
    }
}
